﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SD.Business;
using SD.DataAccess;
using System.Globalization;
        
namespace SD.Web.Views.TeamMaintenance
{
    public partial class EditTeam : System.Web.UI.Page
    {
        /// <summary>
        /// handle event ò page load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCountries();
                lblResult.Visible = false;
                if (Request.Params["teamId"] != null)
                {
                    LoadData();
                }
                else if (Request.Params["departmentId"] != null)
                {
                    int departmentId;
                    if (int.TryParse(Request.Params["departmentId"], out departmentId))
                        HiddenFieldDepartmentId.Value = departmentId.ToString();
                }
                else
                {
                    ButtonSave.Enabled = false;
                    ButtonDeactivate.Enabled = false;
                }
            }

            AddressLookupPopup.SelectedValue += new EventHandler<Web.Controls.Lookup.SelectedValueEventArgs>(AddressLookupPopup_SelectedValue);
        }

        /// <summary>
        /// handle event of address lookup
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void AddressLookupPopup_SelectedValue(object sender, Controls.Lookup.SelectedValueEventArgs e)
        {
            txtAddressLine1.Text = e.Address.AddressLine;
            txtAddressLine2.Text = e.Address.AddressLine2;
            txtAddressLine3.Text = e.Address.AddressLine3;
            txtPostcode.Text = e.Address.Postcode;
            HiddenFieldAddressId.Value = e.Address.AddressId.ToString();
        }

        /// <summary>
        /// load data to controls
        /// </summary>
        private void LoadData()
        {
            //check exist query string
            if (Request.QueryString.Count > 0)
            {
                //if param name in query string is 'User'
                if (Request.Params["teamId"] != null)
                {
                    Team newTeam = TeamBus.GetTeam(Convert.ToInt32(Request.QueryString["teamId"].ToString()));
                    txtTeamName.Text = newTeam.TeamName;
                    txtShortDescription.Text = newTeam.ShortDescription;
                    txtFullDescription.Text = newTeam.FullDescription;
                    txtCityTown.Text = newTeam.CityTown;
                    if (newTeam.Address != null)
                    {
                        txtAddressLine1.Text = newTeam.Address.AddressLine;
                        txtAddressLine2.Text = newTeam.Address.AddressLine2;
                        txtAddressLine3.Text = newTeam.Address.AddressLine3;
                        txtPostcode.Text = newTeam.Address.Postcode;
                    }
                    drpNationCountry.SelectedValue = newTeam.Country.CountryId;
                    txtCounty.Text = newTeam.County;
                    txtEmail.Text = newTeam.Email;
                    txtFax.Text = newTeam.Fax;
                    if (newTeam.Contact != null)
                        txtLeadContact.Text = newTeam.Contact.KnownAs;
                    if (newTeam.BusinessType != null)
                        txtTypeOfBusiness.Text = newTeam.BusinessType.BusinessName;

                    txtPhoneNumber.Text = newTeam.PhoneNumber;
                    txtWebAddress.Text = newTeam.WebAddress;
                    
                    //save data to hiddenfield
                    HiddenFieldDepartmentId.Value = newTeam.DepartmentId.ToString();
                    HiddenFieldContactId.Value = newTeam.ContactId.ToString();
                    HiddenFieldBusinessId.Value = newTeam.BusinessId.ToString();
                    HiddenFieldTeamId.Value = newTeam.TeamId + "";
                    HiddenFieldAddressId.Value = newTeam.AddressId.ToString();

                    if (newTeam.IsActive == true)
                    {
                        LiteralIsActive.Text = "Yes";
                    }
                    else
                    {
                        LiteralIsActive.Text = "No";
                    }
                }
            }
        }

        /// <summary>
        /// Binds the drop down list country.
        /// </summary>
        private void LoadCountries()
        {
            drpNationCountry.DataSource = CountryBO.SelectCountries();
            drpNationCountry.DataBind();
        }

        /// <summary>
        /// Gets the team from fields in page
        /// </summary>
        /// <returns></returns>
        private Team SelectTeam()
        {
            Team team = new Team();
            // get information of team from controls
            team.TeamName = txtTeamName.Text;
            team.ShortDescription = txtShortDescription.Text;
            team.CityTown = txtCityTown.Text;
            team.County = txtCounty.Text;
            team.CountryId = drpNationCountry.SelectedValue;
            team.FullDescription = txtFullDescription.Text;
            team.PhoneNumber = string.IsNullOrEmpty(txtPhoneNumber.Text) ? string.Empty : txtPhoneNumber.Text;
            team.Fax = string.IsNullOrEmpty(txtFax.Text) ? string.Empty : txtFax.Text;
            team.Email = string.IsNullOrEmpty(txtEmail.Text) ? string.Empty : txtEmail.Text;
            team.WebAddress = string.IsNullOrEmpty(txtWebAddress.Text) ? string.Empty : txtWebAddress.Text;

            // get information of team from hiddnfield
            team.ContactId = string.IsNullOrEmpty(HiddenFieldContactId.Value)
                                 ? (int?)null
                                 : int.Parse(HiddenFieldContactId.Value, CultureInfo.CurrentCulture);
            team.AddressId = string.IsNullOrEmpty(HiddenFieldAddressId.Value)
                                 ? (int?)null
                                 : int.Parse(HiddenFieldAddressId.Value, CultureInfo.CurrentCulture);

            team.BusinessId = string.IsNullOrEmpty(HiddenFieldBusinessId.Value)
                                 ? (int?)null
                                 : int.Parse(HiddenFieldBusinessId.Value, CultureInfo.CurrentCulture);
            team.DepartmentId = int.Parse(HiddenFieldDepartmentId.Value, CultureInfo.CurrentCulture);
            return team;
        }

        /// <summary>
        /// handle event of button save click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            lblResult.Visible = true;
            //if update information team
            if (Request.Params["teamid"] != null)
            {
                int id = Convert.ToInt32(Request.QueryString["teamId"].ToString());
                string teamName = txtTeamName.Text;
                Team team;
                bool result = TeamBus.CheckNameWithId(id, teamName);
                if (result == true)
                {
                    team = SelectTeam();
                    team.TeamId = id;

                    if (TeamBus.AmendTeam(team) == true)
                    {
                        lblResult.Text = "Update Team information Success";
                    }
                    else
                        lblResult.Text = "Update Team information Failure";
                }
                else
                {
                    lblResult.Text = "Update Team information Failure";
                }
            }
                // if add new team
            else
            {
                string teamName = txtTeamName.Text;
                bool result = TeamBus.CheckName(teamName);
                if (result == false)
                {
                    Team team = SelectTeam();
                    if (TeamBus.AddTeam(team) == true)
                    {
                        lblResult.Text = "Add New Success";
                    }
                    else
                        lblResult.Text = "Add New Failure";
                }
                else
                    lblResult.Text = "Add New Failure";
            }
        }

        /// <summary>
        /// handle event of button back click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("TeamList.aspx?departmentid={0}", HiddenFieldDepartmentId.Value));
        }

        /// <summary>
        /// handle event of ButtonTypeOfBusiness_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonTypeOfBusiness_Click(object sender, EventArgs e)
        {
            BusinessLookup.Popup();
        }

        /// <summary>
        /// handle event of ButtonContactLookup_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonContactLookup_Click(object sender, EventArgs e)
        {
            ContactLookupPopup.Popup();
        }

        /// <summary>
        /// handle event Selected Index Changed of radio button rdbListAddress
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rdbListAddress_SelectedIndexChanged(object sender, EventArgs e)
        {
            int departmentId;
            if (int.TryParse(HiddenFieldDepartmentId.Value, out departmentId))
            {
                Department department = DepartmentBUS.GetDepartmentById(departmentId);
                if (department != null)
                {
                    Address address = rdbListAddress.SelectedValue.Equals("Organization")
                                          ? department.Directorate.Organization.Address
                                          : department.Address;
                    if (address == null)
                    {
                        return;
                    }

                    txtAddressLine1.Text = address.AddressLine;
                    txtAddressLine2.Text = address.AddressLine2;
                    txtAddressLine3.Text = address.AddressLine3;
                    txtPostcode.Text = address.Postcode;
                    HiddenFieldAddressId.Value = address.AddressId.ToString(CultureInfo.CurrentCulture);
                }
            }
        }

        /// <summary>
        /// handle event of ButtonPostcodeLookup click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonPostcodeLookup_Click(object sender, EventArgs e)
        {
            AddressLookupPopup.Popup();
        }

        /// <summary>
        /// handle event of button ButtonBack Command
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonBack_Command(object sender, CommandEventArgs e)
        {
            int departmentId;
            if (int.TryParse(HiddenFieldDepartmentId.Value, out departmentId))
            {
                Response.Redirect(string.Format(CultureInfo.CurrentCulture, "TeamList.aspx?departmentId={0}", departmentId));
            }
            else
                Response.Redirect(string.Format(CultureInfo.CurrentCulture, "~/default.aspx"));
        }

        /// <summary>
        /// handle event of button ButtonDeactivate Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonDeactivate_Click(object sender, EventArgs e)
        {
            lblResult.Visible = true;
            if (LiteralIsActive.Text == "Yes")
            {
                //update status = true
                bool success = TeamBus.SetStatusInActive(Convert.ToInt32(Request.QueryString["TeamId"].ToString()));
                if (success == true)
                {
                    //LoadData();
                    lblResult.Text = "Edit status successfully!";
                    LiteralIsActive.Text = "No";
                }
            }
            else
            {
                lblResult.Text = "Team is deactived!";
            }
        }
    }
}